package com.gaohe.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaohe.common.R;
import com.gaohe.common.RegexUtils;
import com.gaohe.common.SMSSendCode;
import com.gaohe.mapper.AdminMapper;
import com.gaohe.pojo.*;
import com.gaohe.service.AdminService;
import com.gaohe.service.UserService;
import com.gaohe.utils.CodeUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.statement.ReturningClause;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    //会员分页查询
    @GetMapping("/page")
    public R page(@RequestParam int page,
                  @RequestParam int pageSize,
                  @RequestParam(required = false) String name,
                  @RequestParam String type){
        //分页条件
        Page<User> userPage = new Page<>(page, pageSize);
        //查询条件
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        //多条件查询：链式查询
        qw.like(!StringUtils.isEmpty(name),User::getName,name).
        eq(User::getType,type);
        qw.orderByDesc(User::getUpdateTime);
        //分页查询
        userService.page(userPage,qw);
        return R.success(userPage);
    }
//    //会员查看
      @GetMapping("/user/{id}")
      public R findById(@PathVariable Long id){

        return R.success(userService.getById(id));

      }
     //会员禁用
     @PutMapping("/status")
    public R status(@RequestBody User user){
        //根据ID修改
         boolean b = userService.updateById(user);
         return b?R.success("修改成功"):R.error("修改失败");
     }
     //添加会员
    @PostMapping("/user")
    public R save(@RequestBody User user){
        //字段维护
        user.setStatus(1);
        user.setType("会员");
        boolean b = userService.save(user);
        return b?R.success("新增成功"):R.error("新增失败");

    }
    //新增老师
    @PostMapping("/teacher")
    public R save2(@RequestBody User user){
        //字段维护
        user.setStatus(1);
        user.setType("老师");
        boolean b = userService.save(user);
        return b?R.success("新增成功"):R.error("新增失败");
    }
    //修改老师
    //回显
    @GetMapping("/teacher/{id}")
    public R findbyID(@PathVariable Long id){
        return R.success(userService.getById(id));
    }
    //修改
    @PutMapping("/teacher")
    public R update(@RequestBody User user){
        boolean b = userService.updateById(user);
        return b?R.success("修改成功"):R.error("修改失败");
    }
    //新增课程回显
    @GetMapping("/teacher")
    public R findall(){
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getType,"老师");
        return R.success(userService.list(qw));

    }
    //查询老师的课程
    @GetMapping("/teacher/classes/{id}")
    public R findbyIdtoClass(@PathVariable Long id){
        List<Classes> classes = userService.findbyIdtoClass(id);
        return R.success(classes);
    }
    //查看该会员的所有会员卡
    @GetMapping("/userCards/{id}")
    public R findByIdtoCards(@PathVariable Long id){
        List<UserCard> byIdtoCards = userService.findByIdtoCards(id);
        return R.success(byIdtoCards);
    }
    //为该会员办卡
    @PostMapping("/user/saveByCardId/{cardId}")
    public R saveByCardId(@PathVariable Long cardId,
                          @RequestBody User user
                          )
    {
        Boolean aBoolean = userService.saveByCardId(cardId, user);
        return aBoolean?R.success("添加成功"):R.error("添加失败");

    }
    //查看该会员的全部课程
    @GetMapping("/userClasses/{id}")
    public R findByIdtoClass(@PathVariable Long id){
        List<Classes> byIdtoClass = userService.findByIdtoClass(id);
        return R.success(byIdtoClass);

    }
    @Autowired
    private RedisTemplate redisTemplate;
    //获取验证码
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody Map<String,String> map) {
        //1.接收手机号
        String phone = map.get("phone");
        //2.校验手机号格式
        if(!RegexUtils.isPhoneNumber(phone)){
            return R.error("手机号格式输入有误");
        }
        //3.生成验证码
        Integer code = CodeUtils.generateValidateCode(4);
        log.info("code:{}",code);
        //4.验证码存入redis
        redisTemplate.opsForValue().set("code"+phone,code,5, TimeUnit.MINUTES);
        //5.给用户发短信
//        try {
//            SMSSendCode.sendCode(phone,Strin bg.valueOf(code));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        //返回
        return R.success("验证码发送成功");
    }
    //登录
    @PostMapping("/login")
    public R login(@RequestBody Map<String,String> map){
        //1.接收手机号-校验
        String phone=map.get("phone");
        if(!RegexUtils.isPhoneNumber(phone)){
            return R.error("手机号格式输入有误");
        }
        //2.接收验证码-校验 redis中的验证码比较
       String code=map.get("code");
        if(StringUtils.isEmpty(code)){
            R.error("请输入验证码");
        }
        Object code1 = redisTemplate.opsForValue().get("code"+phone);
        if(StringUtils.isEmpty(code1))
        {
            return R.error("验证码已过期");
        }
        if(!String.valueOf(code1).equals(code)){
            return R.error("验证码输入错误");
        }
        //3.类型非空判断
        String type=map.get("type");
        if(StringUtils.isEmpty(type)){
            return R.error("类型未勾选");
        }
        //4.查询用户详细信息
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getPhone,phone);
        qw.eq(User::getType,type);
        User user = userService.getOne(qw);
        //用户禁用判断
        if(user.getStatus()==0){
            return R.error("用户已被禁用");
        }
        //用户查不到 - 会员
        if(StringUtils.isEmpty(user) && type.equals("huiyuan")){
            user=new User();
            user.setName("_会员_"+phone);
            user.setPhone(phone);
            user.setBirthday(LocalDate.now());
            user.setImage("1726842775346.jpg");
            user.setType("会员");
            user.setUpdateTime(LocalDateTime.now());
            user.setCreateTime(LocalDateTime.now());
            user.setCreateUser(2L);
            user.setUpdateUser(2L);
            userService.save(user);//ID回显



        }
        //用户查不到 - 老师
        if(user==null && type.equals("老师")){
            return R.error("老师未注册，请联系管理员");
        }
        //登录-用户ID存会话-redis
        redisTemplate.opsForValue().set("auth"+user.getId(),user.getId(),30,TimeUnit.MINUTES);
        //返回用户信息
        return R.success(user);
    }
    //小程序
    @GetMapping("/getSelectedCard")
    public R getSelectedCard(@RequestParam Long userId,
                             @RequestParam Long cardId)
    {
        Boolean selectedCard = userService.getSelectedCard(userId, cardId);

        return R.success(selectedCard);
    }
    //用户id 查询用户信息
    //已写过上边网页端









}
